package problem47;

//47.全排列2
//https://leetcode.cn/problems/permutations-ii/?envType=problem-list-v2&envId=array

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    List<List<Integer>> ret;
    List<Integer> list;
    boolean[] st;

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        ret = new ArrayList<>();
        st = new boolean[nums.length];
        list = new ArrayList<>();
        dfs(nums);
        return ret;
    }

    private void dfs(int[] nums) {
        if (list.size() == nums.length) {
            ret.add(new ArrayList(list));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!st[i]) {
                if (i > 0 && !st[i-1] && nums[i] == nums[i - 1]) {
                    continue;
                }
                list.add(nums[i]);
                st[i] = true;
                dfs(nums);
                st[i] = false;
                list.remove(list.size() - 1);
            }
        }
    }
}